package com.innovation.chengzhangriji.service;

import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Timeline;
import com.innovation.chengzhangriji.TimelineAudioUrl;
import com.innovation.chengzhangriji.TimelineMilestone;
import com.innovation.chengzhangriji.TimelinePhoto;
import com.innovation.chengzhangriji.TimelinePhotoUrl;
import com.innovation.chengzhangriji.TimelineText;
import com.innovation.chengzhangriji.TimelineVideoScreenshotUrl;
import com.innovation.chengzhangriji.TimelineVideoUrl;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.FileUploadResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.http.TicketGetRequest;
import com.innovation.chengzhangriji.http.TypeDataResponse;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.event.BaseEvent;

import java.io.File;

import de.greenrobot.event.EventBus;

public class UploadTimelineService extends BaseSyncTimelineService {

    private Toast toast;

    @Override
    protected void onTimelineStartCommand() {
        toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            stopSelf();
            return;
        }
        int babyID = loginInfo.getBabyID();
        String userID = loginInfo.getUserID();
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        uploadTimeline(queryUnSyncTimeline(/** babyID, **/userID), phone, token);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /*上传日记*/

    private void uploadTimeline(Timeline timeline, String phone, String token) {
        if (timeline == null) {
            stopSelf();
            return;
        }

        final int babyID = timeline.getBabyID();
        final String uuid = timeline.getUuid();
        final long createTS = timeline.getCreateTS();
        final int type = timeline.getType();
        final int state = timeline.getState();

        switch (type) {
            case TypeDataResponse.TYPE_TEXT:
                TimelineText text = queryTimelineText(uuid);
                uploadTimelineText(phone, token, uuid, babyID, text.getText(), createTS, state);
                break;
            case TypeDataResponse.TYPE_PHOTO:
                TimelinePhotoUrl photoUrl = queryTimelinePhotoUrl(uuid);
                if (photoUrl == null) {
                    TimelinePhoto timelinePhoto = queryTimelinePhoto(uuid);
                    String photoText = timelinePhoto.getText();
                    String photoTheme = timelinePhoto.getTheme();
                    String[] photoUrls = queryTimelinePhotoUrlUrls(uuid);
                    uploadTimelinePhoto(phone, token, uuid, babyID, photoText, photoTheme, photoUrls, createTS, state);
                } else {
                    if(!new File(photoUrl.getLocalUrl()).exists()) {
                        delete(uuid);
                        onTimelineStartCommand();
                    } else {
                        uploadTimelinePhotoRes(phone, token, photoUrl.getLocalUrl());
                    }
                }
                break;
            case TypeDataResponse.TYPE_AUDIO:
                TimelineAudioUrl audio = queryTimelineAudioUrl(uuid);
                int length = audio.getLength();
                String localUrl = audio.getLocalUrl();
                uploadTimelineAudioRes(phone, token, localUrl, uuid, babyID, length, createTS, state);
                break;
            case TypeDataResponse.TYPE_VIDEO:
                TimelineVideoScreenshotUrl videoScreenshotUrl = queryTimelineVideoScreenshotUrl(uuid);
                String screenshotLocalUrl = videoScreenshotUrl.getLocalUrl();
                TimelineVideoUrl videoUrl = queryTimelineVideoUrl(uuid);
                int videoLength = videoUrl.getLength();
                String videoLocalUrl = videoUrl.getLocalUrl();
                uploadTimelineVideoScreenshotRes(phone, token, screenshotLocalUrl, uuid, babyID, videoLength, videoLocalUrl, createTS, state);
                break;
            case TypeDataResponse.TYPE_MILESTONE:
                TimelineMilestone milestone = queryTimelineMilestone(uuid);
                uploadTimelineMilestone(phone, token, uuid, babyID, milestone.getMilestoneID(), milestone.getMilestone(), createTS, state);
                break;
        }
    }

    private void uploadTimelineText(final String phone, final String token, final String uuid, final int babyID, String text, long createTS, int state) {
        Client.requestTextUpload(this, phone, token, uuid, babyID, text, null, 0, createTS, state, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                //noinspection ConstantConditions
                //insertOrReplaceSeverTime(babyID, get(value.toString(), Long.class));
                updateTimeline(uuid);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                if (value.equals("没有权限执行当前操作")) {
                    toast.setText(value);
                    toast.show();
                    //updateTimeline(uuid);
                    delete(uuid);
                    stopSelf();
                } else {
                    onTimelineStartCommand();
                }
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }
        }, networkUnavailableSampleImpl());
    }

    private void uploadTimelinePhoto(final String phone, final String token, final String uuid, final int babyID, String text, String theme, String[] urls, long createTS, int state) {
        Client.requestPhotoUpload(this, phone, token, uuid, babyID, text, theme, urls, null, 0, createTS, state, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                //noinspection ConstantConditions
                //insertOrReplaceSeverTime(babyID, get(value.toString(), Long.class));
                updateTimeline(uuid);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                if (value.equals("没有权限执行当前操作")) {
                    toast.setText(value);
                    toast.show();
                    //updateTimeline(uuid);
                    delete(uuid);
                    stopSelf();
                } else {
                    onTimelineStartCommand();
                }
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }
        }, networkUnavailableSampleImpl());
    }

    private void uploadTimelineAudio(final String phone, final String token, final String uuid, final int babyID, int length, String url, long createTS, int state) {
        Client.requestAudioUpload(this, phone, token, uuid, babyID, length, url, createTS, state, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                //noinspection ConstantConditions
                //insertOrReplaceSeverTime(babyID, get(value.toString(), Long.class));
                updateTimeline(uuid);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                if (value.equals("没有权限执行当前操作")) {
                    toast.setText(value);
                    toast.show();
                    //updateTimeline(uuid);
                    delete(uuid);
                    stopSelf();
                } else {
                    onTimelineStartCommand();
                }
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }

        }, networkUnavailableSampleImpl());
    }

    private void uploadTimelineVideo(final String phone, final String token, final String uuid, final int babyID, final String screenshotUrl, final int length, final String url, final long createTS, final int state) {
        Client.requestVideoUpload(this, phone, token, uuid, babyID, length, url, screenshotUrl, createTS, state, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                //noinspection ConstantConditions
                //insertOrReplaceSeverTime(babyID, get(value.toString(), Long.class));
                updateTimeline(uuid);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                if (value.equals("没有权限执行当前操作")) {
                    toast.setText(value);
                    toast.show();
                    //updateTimeline(uuid);
                    delete(uuid);
                    stopSelf();
                } else {
                    repeat();
                }
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }

            private void repeat() {
                uploadTimelineVideo(phone, token, uuid, babyID, screenshotUrl, length, url, createTS, state);
            }

        }, networkUnavailableSampleImpl());
    }

    private void uploadTimelineMilestone(final String phone, final String token, final String uuid, final int babyID, int milestoneID, String milestone, long createTS, int state) {
        Client.requestTextUpload(this, phone, token, uuid, babyID, null, milestone, milestoneID, createTS, state, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                //noinspection ConstantConditions
                //insertOrReplaceSeverTime(babyID, get(value.toString(), Long.class));
                updateTimeline(uuid);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                if (value.equals("没有权限执行当前操作")) {
                    toast.setText(value);
                    toast.show();
                    // updateTimeline(uuid);
                    delete(uuid);
                    stopSelf();
                } else {
                    onTimelineStartCommand();
                }
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }
        }, networkUnavailableSampleImpl());
    }

    /*上传资源*/

    private void uploadTimelinePhotoRes(final String phone, final String token, final String localUrl) {
        Client.requestFileUpload(this, phone, token, TicketGetRequest.TYPE_IMAGE, "jpg", new File(localUrl), new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                FileUploadResponse response = get(value.toString(), FileUploadResponse.class);
                if (response == null) {
                    repeat();
                    return;
                }
                String url = response.getUrl();
                updateTimelinePhotoUrl(url, localUrl);
                onTimelineStartCommand();
            }

            @Override
            public void onChZhRJFailure(String value) {
                repeat();
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                stopSelf();
            }

            private void repeat() {
                uploadTimelinePhotoRes(phone, token, localUrl);
            }

        }, networkUnavailableSampleImpl());
    }

    private void uploadTimelineAudioRes(final String phone, final String token, final String localUrl, final String uuid, final int babyID, final int length, final long createTS, final int state) {
        if(TextUtils.isEmpty(localUrl) || !new File(localUrl).exists()) {
            delete(uuid);
            onTimelineStartCommand();
        } else {
            Client.requestFileUpload(this, phone, token, TicketGetRequest.TYPE_AUDIO, "amr", new File(localUrl), new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    FileUploadResponse response = get(value.toString(), FileUploadResponse.class);
                    if (response == null) {
                        repeat();
                        return;
                    }
                    String url = response.getUrl();
                    updateTimelineAudioUrl(url, localUrl);
                    uploadTimelineAudio(phone, token, uuid, babyID, length, url, createTS, state);
                }

                @Override
                public void onChZhRJFailure(String value) {
                    repeat();
                }

                @Override
                public void onChZhRJTokenFailure(String value) {
                    stopSelf();
                }

                private void repeat() {
                    uploadTimelineAudioRes(phone, token, localUrl, uuid, babyID, length, createTS, state);
                }

            }, networkUnavailableSampleImpl());
        }
    }

    private void uploadTimelineVideoScreenshotRes(final String phone, final String token, final String screenshotLocalUrl, final String uuid, final int babyID, final int length, final String localUrl, final long createTS, final int state) {
        if(TextUtils.isEmpty(screenshotLocalUrl) || !new File(screenshotLocalUrl).exists() || !new File(localUrl).exists()) {
            delete(uuid);
            onTimelineStartCommand();
        } else {
            Client.requestFileUpload(this, phone, token, TicketGetRequest.TYPE_IMAGE, "jpg", new File(screenshotLocalUrl), new ResponseHandler() {
                @Override
                public void onInnovationSuccess(JsonElement value) {
                    FileUploadResponse response = get(value.toString(), FileUploadResponse.class);
                    if (response == null) {
                        repeat();
                        return;
                    }
                    String screenshotUrl = response.getUrl();
                    updateTimelineVideoScreenshotUrl(screenshotUrl, screenshotLocalUrl);
                    uploadTimelineVideoRes(phone, token, TicketGetRequest.TYPE_VIDEO, "mp4", localUrl, uuid, babyID, screenshotUrl, length, createTS, state);
                }

                @Override
                public void onChZhRJFailure(String value) {
                    repeat();
                }

                @Override
                public void onChZhRJTokenFailure(String value) {
                    stopSelf();
                }

                private void repeat() {
                    uploadTimelineVideoScreenshotRes(phone, token, screenshotLocalUrl, uuid, babyID, length, localUrl, createTS, state);
                }

            }, networkUnavailableSampleImpl());
        }
    }

    private void uploadTimelineVideoRes(final String phone, final String token, final int type, final String ext, final String localUrl, final String uuid, final int babyID, final String screenshotUrl, final int length, final long createTS, final int state) {
        if(TextUtils.isEmpty(localUrl) || !new File(localUrl).exists()) {
            delete(uuid);
            onTimelineStartCommand();
        } else {
            Client.requestFileUpload(this, phone, token, type, ext, new File(localUrl), new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    FileUploadResponse response = get(value.toString(), FileUploadResponse.class);
                    if (response == null) {
                        repeat();
                        return;
                    }
                    String url = response.getUrl();
                    updateTimelineVideoUrl(url, localUrl);
                    uploadTimelineVideo(phone, token, uuid, babyID, screenshotUrl, length, url, createTS, state);
                }

                @Override
                public void onChZhRJFailure(String value) {
                    repeat();
                }

                @Override
                public void onChZhRJTokenFailure(String value) {
                    stopSelf();
                }

                private void repeat() {
                    uploadTimelineVideoRes(phone, token, type, ext, localUrl, uuid, babyID, screenshotUrl, length, createTS, state);
                }

            }, networkUnavailableSampleImpl());
        }
    }

    /*数据库操作*/

    private Timeline queryUnSyncTimeline(/** int babyID, **/String userID) {
        return DatabaseManager.getInstance(this).queryUnSyncTimeline(/** babyID, **/userID);
    }

    private TimelineText queryTimelineText(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelineText(uuid);
    }

    private TimelinePhoto queryTimelinePhoto(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelinePhoto(uuid);
    }

    private TimelinePhotoUrl queryTimelinePhotoUrl(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelinePhotoUrl(uuid, 0);
    }

    private String[] queryTimelinePhotoUrlUrls(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelinePhotoUrlUrls(uuid);
    }

    private TimelineAudioUrl queryTimelineAudioUrl(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelineAudioUrl(uuid);
    }

    private TimelineVideoScreenshotUrl queryTimelineVideoScreenshotUrl(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelineVideoScreenshotUrl(uuid);
    }

    private TimelineVideoUrl queryTimelineVideoUrl(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelineVideoUrl(uuid);
    }

    private TimelineMilestone queryTimelineMilestone(String uuid) {
        return DatabaseManager.getInstance(this).queryTimelineMilestone(uuid);
    }

    private void updateTimelinePhotoUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateTimelinePhotoUrl(url, localUrl);
    }

    private void updateTimelineAudioUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateTimelineAudioUrl(url, localUrl);
    }

    private void updateTimelineVideoScreenshotUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateTimelineVideoScreenshotUrl(url, localUrl);
    }

    private void updateTimelineVideoUrl(String url, String localUrl) {
        DatabaseManager.getInstance(this).updateTimelineVideoUrl(url, localUrl);
    }

    private void updateTimeline(String uuid) {
        DatabaseManager.getInstance(this).updateTimeline(uuid);
    }

    private void delete(String uuid) {
        // 删除当条，刷新首页.
        DatabaseManager.getInstance(this).deleteUnSyncTimeline(uuid);
        // 发送删除日记通知
//        BaseEvent event = new BaseEvent(BaseEvent.TYPE_SEND_DIARY_FAILURE);
//        EventBus.getDefault().post(event);
    }
}
